package com.mifengs.mall.ui.main;


import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.LazyFragment;
import com.mifengs.mall.di.component.DaggerFloorFrgComponent;
import com.mifengs.mall.di.module.FloorFrgModule;
import com.mifengs.mall.entity.FloorBean;
import com.mifengs.mall.entity.TabBean;
import com.mifengs.mall.floor.FloorListAdapter;
import com.mifengs.mall.widget.BlankPageView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * A simple {@link Fragment} subclass.
 */
public class FloorFragment extends LazyFragment<FloorFrgPresenter> implements FloorFrgContract.View ,BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private boolean isFirst;

    private View view;
    private enum LoadStaus{
        FLOOR,
        OTHER_FLOOR
    }

    private TabBean mTabBean;

    private FloorListAdapter mFloorListAdapter;

    private List<FloorBean> mFloorBeanList = new ArrayList<>();

    private int mFloorCurrentPage =1;

    private int mLikeCurrentPage =1;

    private LoadStaus mLoadStaus;

    private static final String NO_RECOMMENDTYPE = "0";

    private static final String LIKE_RECOMMENDTYPE = "1";


    public FloorFragment() {

    }


    public static FloorFragment newInstance(TabBean tabBean) {
        FloorFragment fragment = new FloorFragment();
        Bundle args = new Bundle();
        args.putSerializable("tab", tabBean);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        isFirst = true;
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mTabBean = (TabBean) getArguments().getSerializable("tab");
        }
    }



    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void initInjector() {
        super.initInjector();
        DaggerFloorFrgComponent.builder()
                .floorFrgModule(new FloorFrgModule(this))
                .build()
                .inject(this);
    }

    private void init() {
        mFloorCurrentPage = 1;
        mLikeCurrentPage = 1;
       // mTabBean.setRecommendType("1");
        mLoadStaus = LoadStaus.FLOOR;
        mRvList.setLayoutManager(new LinearLayoutManager(getContext()));
        mFloorListAdapter = new FloorListAdapter(mFloorBeanList);
        mFloorListAdapter.setOnLoadMoreListener(this,mRvList);
        mFloorListAdapter.openLoadAnimation();
        mRvList.setAdapter(mFloorListAdapter);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                Glide.get(getContext()).clearMemory();
                mFloorCurrentPage = 1;
                mLikeCurrentPage = 1;
                mLoadStaus = LoadStaus.FLOOR;
                mPresenter.getData(mFloorCurrentPage,true);
            }
        });
        mRefreshLayout.setEnableLoadMore(false);


        BlankPageView blankPageView = new BlankPageView(getContext());
        blankPageView.initViewData(BlankPageView.no_floor_data);
        mFloorListAdapter.setEmptyView(blankPageView);
    }


    @Override
    public void onDestroyView() {
        if(view != null){
            unbindDrawables(view);
        }
        super.onDestroyView();

    }



    private void unbindDrawables(View view)
    {
        if (view.getBackground() != null)
        {
            view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup && !(view instanceof AdapterView))
        {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
            {
                unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            ((ViewGroup) view).removeAllViews();
        }
    }

    @Override
    protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_floor, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }



    @Override
    protected void initData() {
        mPresenter.getData(mFloorCurrentPage,false);
    }

    @Override
    public void setFloors(final List<FloorBean> beanList, boolean isLoadOver) {
       // mFloorListAdapter.setNewData(beanList);
        changeLoadStatus(isLoadOver);
        if(isLoadOver){
            switch (mLoadStaus) {
                case FLOOR:
                    mRvList.post(new Runnable() {
                        @Override
                        public void run() {
                            mFloorListAdapter.setNewData(beanList);
                            mFloorListAdapter.loadMoreEnd(true);
                        }
                    });
                    break;
                case OTHER_FLOOR:
                    mFloorListAdapter.setNewData(beanList);
                    break;
            }
        }else{
            mFloorListAdapter.setNewData(beanList);
        }
    }

    @Override
    public void setMoreFloors(final List<FloorBean> beanList, final boolean isLoadOver) {
        changeLoadStatus(isLoadOver);
        mRvList.post(new Runnable() {
            @Override
            public void run() {
                mFloorListAdapter.addData(beanList);
                if(isLoadOver){
                    switch (mLoadStaus) {
                        case FLOOR:
                            mFloorListAdapter.loadMoreEnd(true);
                            break;
                        case OTHER_FLOOR:
                            loadMoreComplete();
                            break;
                    }
                }else{
                    loadMoreComplete();
                }
            }
        });
    }

    @Override
    public String getTabId() {
        return mTabBean.getId();
    }

    @Override
    public void finishRefresh() {
        if(mRefreshLayout !=null)
        mRefreshLayout.finishRefresh();
    }

//    @OnClick({R.id.iv_to_sign, R.id.iv_to_top})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.iv_to_sign:
//                if(PreferenceUtils.getLoginStatus()){
//                    ToIntentUtil.toCommonIntent(Constant.H5_sign,getActivity());
//                }else{
//                    startActivity(new Intent(getActivity(), LoginActivity.class));
//                }
//                break;
//            case R.id.iv_to_top:
//                mRvList.smoothScrollToPosition(0);
//                break;
//        }
//    }

    @Override
    public void onLoadMoreRequested() {
        switch (mLoadStaus) {
            case FLOOR:
                mFloorCurrentPage++;
                mPresenter.getData(mFloorCurrentPage,false);
                break;
            case OTHER_FLOOR:
                mPresenter.getLikeGoods(mLikeCurrentPage);
                mLikeCurrentPage++;
                break;
        }

    }

    @Override
    public void loadMoreComplete() {
        mFloorListAdapter.loadMoreComplete();
    }


    public void changeLoadStatus(boolean isFloorLoadover){
        if(NO_RECOMMENDTYPE.equals(mTabBean.getRecommendType())){
            mLoadStaus = LoadStaus.FLOOR;
        }else if (LIKE_RECOMMENDTYPE.equals(mTabBean.getRecommendType())){
            if (isFloorLoadover) {
                mLoadStaus = LoadStaus.OTHER_FLOOR;
            }else{
                mLoadStaus = LoadStaus.FLOOR;
            }
        }
    }

    @Override
    public void setLikeFloors(List<FloorBean> beanList) {

    }

    @Override
    public void setMoreLikeFloors(final List<FloorBean> beanList) {
        mRvList.post(new Runnable() {
            @Override
            public void run() {
                mFloorListAdapter.addData(beanList);
                int nowPagesize = 0;
                if(beanList.size()>0){
                    nowPagesize = beanList.get(0).getAdverts().size();
                }
                if(nowPagesize  == FloorFrgPresenter.LIKE_PAGE_LIKE){
                    loadMoreComplete();
                }else{
                    mFloorListAdapter.loadMoreEnd(true);
                }

            }
        });
    }

    @Override
    public void loadMoreFail() {
        mFloorListAdapter.loadMoreFail();
    }

    @Override
    public void refreshloading() {
        if(mRefreshLayout!=null)
        mRefreshLayout.autoRefresh();
    }


    @Override
    public int getItemCount(){
        return mFloorListAdapter.getItemCount();
    }


    /**
     * 判断是否从网络中加载还是使用缓存，如果已经创建过了使用缓存，如果没有使用网络上的数据
     * @return
     */
    @Override
    public boolean isFirst() {
        return isFirst;
    }

    @Override
    public void setFirst(boolean isFirst) {
        this.isFirst = isFirst;
    }

}
